<template>
  <div class="list-content">
    <el-form :inline="true" :model="formInline" class="demo-form-inline" @submit.native.prevent>
      <el-form-item v-if="isMuilUnitUser">
        <el-select filterable @change="getStatis()" v-model="formInline.orgIds" placeholder="请选择业主单位">
          <el-option
            v-for="item in orgOptions"
            :key="item.organizationId"
            :label="item.shortName"
            :value="item.organizationId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="formInline.time"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
          @change="getStatis()"
          >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button class="form-search-btn" type="primary" @click="getStatis()">查询</el-button>
      </el-form-item>
    </el-form>
    <el-row v-loading="loading">
      <el-col :span="24">
        <div class="grid-content">
          <div class="chart-heaad">安全评估</div>  
          <div id="finishRate_unitSafetyAnalysis" class="chart-content"></div>
          <div id="inspectorRate_unitSafetyAnalysis" class="chart-content"></div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { qnToken} from '@/api/api'
import * as Dao from '@/api/analysisReport'
import { getOrgList} from '@/api/org'
import util from '@/utils/util'

export default {
  name: 'UnitSafetyAnalysis',
  props:['param'],
  data () {
    return {
      pickerOptions: $.extend({
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },util.intTimePickerOptions()),
      freashStaticFlag:0,
      formInline: {
        orgIds:this.$store.state.userinfo.isMuilUnitUser ? this.$store.state.userinfo.organizationIds : this.$store.state.userinfo.org.id,
        time:'',
      },
      util:util,
      isMuilUnitUser:this.$store.state.userinfo.isMuilUnitUser,
      accountName:this.$store.state.userinfo.accountName,
      orgOptions: [{organizationId: this.$store.state.userinfo.organizationIds,shortName: "全部业主单位"}],
      loading: false,
      colorList:[
                  '#70bbea','#5c90d2','#a58ad4','#f3b75e','#ea4f63',
                   '#16adc4','#9BCA63','#FAD860','#F3A43B','#60C0DD',
                   '#D7504B','#C6E579','#F4E001','#F0805A','#26C0C0'
                ]
    }
  },
  created:function() {
    //默认一个月
    let end = new Date();
    let start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
    this.formInline.time = [util.ilinkTimeformat.format(start, 'yyyy-MM-dd ')+'00:00:00', util.ilinkTimeformat.format(end, 'yyyy-MM-dd ')+'23:59:59']
    //绑定下拉框
    if(this.isMuilUnitUser){
      getOrgList({queryType: 0}).then((data)=>{
        this.orgOptions.push.apply(this.orgOptions,data.data);
      })
    }
   this.getStatis()
  },
  methods: {
    getStatis() {
      let that = this
      that.loading = true
      Dao.getOrgSafetyDurationCount({
        orgIds: that.formInline.orgIds,
        startTime: that.formInline.time?(that.formInline.time[0].split(' ')[0]+' 00:00:00'):'',
        endTime: that.formInline.time?(that.formInline.time[1].split(' ')[0]+' 23:59:59'):'',
      }).then((data)=>{
        that.loading = false
        let result = data.data
        let value1= result.securityDurationSum||0
        let value2= result.dangerDurationSum||0
        let value3= result.urgentDurationSum||0
        let total = util.accAdd(util.accAdd(value1, value2), value3)
        //画图
        let option_echart = {
            title: {
                textStyle: { color: '#2F3444', fontSize: '16' },
                y: 'left',
                left: '35',
                top: '0',
                text: '安全态势时长分布（小时）',
            },
            tooltip: {
                trigger: 'item',
                formatter: /*{a} <br/>*/"{b}: {c} ({d}%)"
            },
            color:['rgba(71, 207, 173, 1)','rgba(255, 179, 45, 1)','rgba(253, 94, 94, 1)'],
            legend: {
                show:true,
                orient:'vertical',
                right:0,
                top:'center',
                itemHeight:18,
                itemWidth:18,
                itemGap:35,
                borderRadius:18,
                textStyle: {
                  padding:5,
                  rich: {
                      a: {
                          fontSize:22,
                          fontWeight:'bold',
                          color: 'rgba(47, 52, 68, 1)',
                      },
                      b: {
                          fontSize:22,
                          color: 'rgba(95, 104, 132, 1)',
                          padding:20
                      },
                  },
                },
                // 在文本中，可以对部分文本采用 rich 中定义样式。
                // 这里需要在文本中使用标记符号：
                // `{styleName|text content text content}` 标记样式名。
                // 注意，换行仍是使用 '\n'。
                formatter: function (name) {
                  if(name == '安全'){
                    return'{a|安全}{b|'+value1+'小时，占比'+util.completionDegree(value1,total)+'%}'
                  }else if(name == '危险'){
                    return'{a|危险}{b|'+value2+'小时，占比'+util.completionDegree(value2,total)+'%}'
                  }else{
                    return'{a|告急}{b|'+value3+'小时，占比'+util.completionDegree(value3,total)+'%}'
                  }
                },
                data:[{
                  name: '安全',
                  icon: 'circle'
                },{
                  name: '危险',
                  icon: 'circle',
                },{
                  name: '告急',
                  icon: 'circle',
                }]
            },
            series: [
                {
                    name:'安全',
                    type:'pie',
                    hoverOffset:0,
                    hoverAnimation:false,
                    radius: ['85%', '90%'],
                    avoidLabelOverlap: false,
                    label: {
                      show:true,
                      normal: {
                          // 在文本中，可以对部分文本采用 rich 中定义样式。
                          // 这里需要在文本中使用标记符号：
                          // `{styleName|text content text content}` 标记样式名。
                          // 注意，换行仍是使用 '\n'。
                          formatter: [
                              '{a|'+total+'}',
                              '{b|已监管时长（小时）}'
                          ].join('\n'),
                          rich: {
                              a: {
                                  fontSize:40,
                                  fontWeight:'bold',
                                  color:'rgba(47,52,68,1)',
                              },
                              b: {
                                  fontSize: 12,
                                  lineHeight: 20,
                                  color:'rgba(105, 115, 125, 1)',
                              },
                          },
                          show: true,
                          position: 'center'
                      },
                      emphasis: {
                          show: false,
                      }
                    },
                    labelLine: {
                        normal: {
                            show: false
                        }
                    },
                    data:[
                        {value:value1, name:'安全',itemStyle:{color:'rgba(71, 207, 173, 1)'}},
                        {value:total-value1, name:'其他',itemStyle:{color:'rgba(238,240,244,0.8)'}, tooltip: {show: false}},
                    ]
                },
                 {
                    name:'危险',
                    type:'pie',
                    hoverOffset:0,
                    hoverAnimation:false,
                    radius: ['70%', '75%'],
                    avoidLabelOverlap: false,
                    label: {
                      normal: {
                          show: false,
                      },
                      emphasis: {
                        show: false,
                      }
                    },
                    labelLine: {
                        normal: {
                            show: false
                        }
                    },
                    data:[
                        {value:value2, name:'危险',itemStyle:{color:'rgba(255, 179, 45, 1)'}},
                        {value:total-value2, name:'其他',itemStyle:{color:'rgba(238,240,244,0.8)'}, tooltip: {show: false}},
                    ]
                },
                {
                    name:'告急',
                    type:'pie',
                    hoverOffset:0,
                    hoverAnimation:false,
                    radius: ['55%', '60%'],
                    avoidLabelOverlap: false,
                    label: {
                      normal: {
                          show: false,
                      },
                      emphasis: {
                        show: false,
                      }
                    },
                    labelLine: {
                        normal: {
                            show: false
                        }
                    },
                    data:[
                        {value:value3, name:'告急',itemStyle:{color:'rgba(253, 94, 94, 1)'}},
                        {value:total-value3, name:'其他',itemStyle:{color:'rgba(238,240,244,0.8)'}, tooltip: {show: false}},
                    ]
                }
            ]
        };
        that.$echarts.init(document.getElementById('finishRate_unitSafetyAnalysis')).setOption(option_echart, true); 
        //最危险单位TOP10
        if(that.isMuilUnitUser){
          let orgList = result.orgDetail.slice(0,10)
          let xData1 = [];
          let yData1 = [];
          $.each(orgList,(index,obj)=>{
            xData1.push(obj.orgName);
            yData1.push(obj.urgentDuration);
          })
          that.$echarts.init(document.getElementById('inspectorRate_unitSafetyAnalysis')).setOption({
              title: {
                  textStyle: { color: '#2F3444', fontSize: '16' },
                  y: 'left',
                  left: '35',
                  top: '0',
                  text: '最危险单位TOP10',
                  subtext:'告急时长（小时）',
                  subtextStyle:{
                    lineHeight:30,
                  }
              },
              grid: {
                  left: '5%',
                  right: '5%',
                  top:'20%'
              },
              tooltip: {
                  trigger: 'axis',
                  formatter: "{b}: {c}",
                  axisPointer: { // 坐标轴指示器，坐标轴触发有效
                      type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                  }
              },
              xAxis: {
                  type: 'category',
                  axisTick: {
                      show: false
                  },
                  triggerEvent: true,
                  axisLine: {
                      show: true,
                      lineStyle: {
                          color: 'rgba(55, 139, 246, 0.8)',
                          width: 1, //这里是为了突出显示加上的
                      }
                  },
                  axisLabel: {
                      show: true,
                      textStyle: {
                          color: '#2F3444',
                          fontSize: 14
                      },
                      //interval:xInterval
                  },
                  //max:30,
                  boundaryGap: true,
                  data: xData1
              },
              yAxis: {
                  type: 'value',
                  axisTick: {
                      show: false
                  },
                  //min:minLeavel,
                  //max:maxLeavel,
                  axisLine: {
                      show: false,
                  },
                  axisLabel: {
                      formatter: '{value}',
                      show: true,
                      textStyle: {
                          color: '#2F3444',
                          fontSize: 14
                      }
                  },
                  splitLine: {
                      lineStyle: {
                          color: 'rgba(55, 139, 246, 0.8)',
                          opacity: 0.7
                      }
                  },
                  axisPointer: {
                      snap: true
                  },
                  minInterval: 1
              },
              series: [{
                  name: "告急时长（小时）",
                  type: 'bar',
                  barWidth: '30',
                  itemStyle: {
                    barBorderRadius:[4,4,0,0],
                    color: function(params) {
                        return that.colorList[params.dataIndex]
                    },
                  },
                  label: {
                      normal: {
                          show: false,
                          position: 'inside'
                      }
                  },
                 data: yData1
              }]
          }, true);
        } 
      })
      if(!that.isMuilUnitUser){
        Dao.getOrgScoreByTime({
          orgId: that.formInline.orgIds,
          timeType: 13,
          startTime: that.formInline.time?(that.formInline.time[0].split(' ')[0]+' 00:00:00'):'',
          endTime: that.formInline.time?(that.formInline.time[1].split(' ')[0]+' 23:59:59'):'',
        }).then((data)=>{
          that.loading = false
          let xData = []
          let toolTipData = []
          let yData = []
          let Average = 0
          let Sum = 0
          let Min = 100
          let Max = 0
          $.each(data.data,(index,obj)=>{
            let _finishPercent = parseFloat(obj.score) 
            xData.push( util.ilinkTimeformat.format(new Date(obj.createTime),'M.dd'))
            toolTipData.push( obj.createTime)
            yData.push(_finishPercent)
            Sum+=_finishPercent
            if(Max<_finishPercent){
              Max=_finishPercent;
            } 
            if(Min>_finishPercent){
              Min=_finishPercent;
            } 
          })
          Average = data.data.length==0?0:(Sum/data.data.length)
          //画图
          let option_echart = {
            title: {
                textStyle: { color: '#2F3444', fontSize: '16' },
                y: 'left',
                left: '35',
                top: '0',
                text: '安全评估得分变化（分）',
            },
            grid: {
                left: '55px',
                right: '55px',
            },
            tooltip: {
                trigger: 'axis',
                formatter:function(params){
                  return (toolTipData[params[0].dataIndex]+'<br/>'+ params[0].data+'分')
                }
            },
            xAxis: {
                type: 'category',
                axisTick: { show: false },
                boundaryGap: false,
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: 'rgba(105, 115, 125, 0.3)',
                        width: 1, //这里是为了突出显示加上的
                        type:'dotted'
                    }
                },
                axisLabel: {
                    show: true,
                    textStyle: {
                        color: 'rgba(95, 104, 132, 1)',
                        fontSize: 16
                    },
                    padding:[10,0,0,0]
                    //interval:xInterval
                },
                data: xData
            },
            yAxis: {
                type: 'value',
                axisTick: { show: false },
                axisLine: {
                    show: true,
                    lineStyle: {
                        color: 'rgba(105, 115, 125, 0.3)',
                        width: 1, //这里是为了突出显示加上的
                        type:'dotted'
                    }
                },
                axisLabel: {
                    formatter:function(value){
                      return value||0
                    },
                    show: true,
                    padding:[0,5,0,0],
                    textStyle: {
                        color: 'rgba(136,144,171,1)',
                        fontSize: 14
                    }
                },
                splitLine: {
                    lineStyle: {
                        color: 'rgba(105, 115, 125, 0.3)',
                        width: 1, //这里是为了突出显示加上的
                        type:'dotted'
                    }
                },
            },
            series: [{
                name: "完成率",
                type: 'line',
                smooth: true,
                //areaStyle: { normal: {} },
                symbol:"circle",
                symbolSize:0,
                itemStyle: {
                    normal: {
                        lineStyle:{
                            width:6,//折线宽度
                        },
                        color:"rgba(76, 164, 254, 1)"//折线颜色
                    },
                    emphasis: {
                        color: 'rgba(80, 115, 184, 1)'
                    },
                },
                markLine: {
                  itemStyle:{
                    normal:{
                      lineStyle:{
                        type:'solid',
                        color:'rgba(71, 207, 173, 1)',
                        width:2
                      },
                      label:{
                        show:true,
                        position:"middle",//'start' 线的起始点。'middle' 线的中点。'end' 线的结束点。
                        formatter:function(param){
                          return param.name+param.value+'分'
                        },
                        textStyle: {
                            fontSize: 16,
                        },
                      }
                    }
                  },
                  silent: false,
                  symbolSize:0,
                  data: [{
                      name: '平均值：',
                      yAxis: Average
                  }]
                },
                data: yData
            }]
          };
          that.$echarts.init(document.getElementById('inspectorRate_unitSafetyAnalysis')).setOption(option_echart, true); 
        })
      }
    },
  },
}
</script>
<style lang="scss" scoped>
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
    .chart-heaad{
      height:25px;
      line-height:25px;
      font-size:18px;
      font-weight:500;
      color:rgba(68, 107, 222, 1);
      -webkit-text-stroke:1px rgba(68, 107, 222, 1);
      text-stroke:1px rgba(68, 107, 222, 1);
    }
    .chart-content{
      margin-top: 20px;
      height: 350px;
      width: 100%;
    }
  }
</style>